import { defineStore } from 'pinia'

type State = {
    cart: CartProduct[]
}

const useCartStore = defineStore<
    string,
    State,
    {
        allChecked: (state: State) => boolean
        allTotalMoney: (state: State) => number
    },
    {
        addToCart: (prod: CartProduct) => void
        removeFromCart: (id: string) => void
        modifyAllChecked: (checked: boolean) => void

    }
>('cart', {
    state() {
        return {
            cart: [] as CartProduct[],//保存购物车中所有选购的商品
        }
    },

    getters: {
        allChecked: (state) => state.cart.every(prod => prod.checked),
        allTotalMoney: (state) =>
            state.cart.reduce(
                (sum, curr: any) =>(sum +=  curr.checked ? curr.price * 100 * (curr.amount as number) : 0),0
            )

    },

    actions: {
        /**
         * 加入购物车
         * @param prod 
         */
        addToCart(prod) {
            // 购物车中是否已存在当前选购的商品
            const exist = this.cart.find((curr) => curr.id === prod.id)
            if (exist) {
                exist.amount = (exist.amount ?? 0) + 1
            } else {
                this.cart.push({
                    ...prod,
                    amount: 1,
                    checked: true,//默认选中，以便结算
                })
            }
        },
        removeFromCart(id) {
            this.cart = this.cart.filter((prod) => prod.id !== id)
        },
        /**
         * 切换全选/取消全选
         */
        modifyAllChecked(checked) {
            this.cart.forEach((prod) => {
                prod.checked = checked
            })
        },
    },
    persist: true,
})

export default useCartStore